﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Authorization;

namespace ABPIdentityDemo.Auth
{
    public class ABPPermissionHandler : IAuthorizationHandler
    {
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            // 当前访问 Controller/Action 所需要的权限(策略授权)
            IAuthorizationRequirement[] pendingRequirements = context.PendingRequirements.ToArray();

            IEnumerable<Claim> claims = context.User?.Claims;
            if (claims is null)
            {
                context.Fail();
                return Task.CompletedTask;
            }

            Claim userName = claims.FirstOrDefault(s => s.Type == ClaimTypes.Name);
            if (userName is null)
            {
                context.Fail();
                return Task.CompletedTask;
            }
            var user = UserInfoData.Users
                        .FirstOrDefault(s => string.Equals(s.Email, userName.Value, StringComparison.OrdinalIgnoreCase));
            var permissions = user.Role.Permissions;
            var isAccessDeny = false;
            // 逐个检查
            foreach (IAuthorizationRequirement requirement in pendingRequirements)
            {
                var permissionRequirement = requirement as PermissionRequirement;
                if (!permissions.Any(s => s == permissionRequirement.PermissionName))
                {
                    isAccessDeny = true;
                }
                else
                {
                    context.Succeed(requirement);
                }
            }
            if(isAccessDeny == true)
            {
                context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}
